import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Detail from '@/views/detail'
import Login from '@/views/login'
import Register from '@/views/register'
import Like from '@/views/like'
import Article from '@/views/article'
import Collect from '@/views/collect'
import User from '@/views/user'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const routes = [
  // 提示: 不要忘记了，一级路由还有个出口，在App.vue
  // 首屏: '/'
  {
    path: '/',
    component: Layout,
    // 重定向: 到面经列表
    redirect: '/article',
    // 二级路由: 面经 + 收藏 + 喜欢 + 我的
    children: [
      { path: '/', redirect: '/article' },
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  },
  // 详情:'/detail/41169'
  { path: '/detail/:id', component: Detail },
  // 登录:'/login'
  { path: '/login', component: Login },
  // 注册:'/register'
  { path: '/register', component: Register }
]

const router = new VueRouter({
  routes
})
// 全局前置守卫：在路由跳转时，页面渲染之前，会被自动调用的，在路由导出之前配置好
// to: 路由要去哪里
// from: 路由从哪里来
// next: 根据需求，做条件判断，决定是否放行该路由没进入下一个页面

// 白名单
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // 1. 获取token，并判断是否有token
  const token = getToken()
  if (token) {
    // 2. 如果有token，想去哪儿就去哪儿，放行 next()
    next()
  } else {
    // 3. 如果无token，判断是否是白名单页面
    if (whiteList.includes(to.path)) {
      //   3.1 是，放行 next()
      next()
    } else {
      //   3.2 否，拦截到登录页 next('/login')
      next('/login')
    }
  }
})
export default router
